<template>
  <el-upload
    ref="uploadRef"
    v-model:file-list="fileLists"
    :data="uploadData"
    accept=".pdf"
    :action="`${baseUrl}${apiUrl}`"
    :auto-upload="true"
    :before-upload="handleBeforeUpload"
    v-loading="loading"
    :headers="{ Authorization: token }"
    :limit="1"
    :on-error="handleError"
    :on-exceed="handleExceed"
    :on-success="handleSuccess"
    :on-remove="handleRemove"
    class="my-pdf-upload"
  >
    <div class="upload-body">
      <div class="el-upload__text">
        <span>点击上传文件</span>
      </div>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        <vab-icon icon="information-2-line" style="font-size: 12px; color: #e6a23c" />
        <em>只能上传pdf文件,且不超过{{ fileMax }}MB</em>
      </div>
    </template>
  </el-upload>
</template>

<script lang="ts" setup>
import { ElUpload, genFileId, UploadProps, UploadRawFile } from 'element-plus'

import { useUserStore } from '/@/store/modules/user'
const $baseMessage = inject<any>('$baseMessage')
const userStore = useUserStore()
const token = userStore.getToken
const baseUrl = ref(import.meta.env.VITE_APP_BASE_URL)
const apiUrl = ref('/api/ossPut')

const loading = ref<any>(false)
const uploadRef = ref<InstanceType<typeof ElUpload>>()
const fileLists = ref<any>([])
const fileMax = ref<any>(5)

const uploadData = ref<any>({
  // activityId: '',type: '',
})

const emit = defineEmits(['update:modelValue'])

const props = defineProps({
  modelValue: { type: String, default: '' }, // PDF路径 默认是 modelValue
})

const handleBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const isxlsx = rawFile.name.substring(rawFile.name.length - 3) === 'pdf'
  const isLt20M = rawFile.size! / 1024 / 1024 < fileMax.value
  if (!isxlsx) $baseMessage('上传文件只能是pdf格式!', 'error', 'vab-hey-message-error')
  else if (!isLt20M) $baseMessage(`上传文件大小不能超过 ${fileMax.value}MB!`, 'error', 'vab-hey-message-error')
  else loading.value = true
  return isxlsx && isLt20M
}

const handleExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
  uploadRef.value?.submit()
}

// 上传失败
const handleError: UploadProps['onError'] = (err) => {
  $baseMessage(JSON.parse(err.message ?? '{}')?.message, 'error', 'vab-hey-message-error')
  loading.value = false
}

// 上传成功
const handleSuccess: UploadProps['onSuccess'] = (res) => {
  loading.value = false
  if (res?.status == 200) {
    $baseMessage('上传成功', 'success', 'vab-hey-message-success')
    // uploadRef.value!.clearFiles()
    emit('update:modelValue', res.url)
  } else $baseMessage('上传失败', 'error', 'vab-hey-message-error')
}

// 删除文件
const handleRemove = (res: any) => {
  // console.log('res删除', res)
  emit('update:modelValue', '')
}

const handleSubmit = () => {
  uploadRef.value?.submit()
}

// 初始化 赋值
const handleInit = (initUrl?: any) => {
  fileLists.value = [{ name: '合同/确认书.pdf', url: initUrl }]
}

// 关闭 清空数据
const handleClose = () => {
  fileLists.value = []
  uploadRef.value!.clearFiles()
}

defineExpose({
  handleSubmit,
  handleInit,
  handleClose,
})
</script>

<style lang="scss">
.my-pdf-upload {
  .upload-body {
    padding: 0 20px;
    width: 180px;
    height: 50px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #fafcff;
    font-size: 14px;
    font-weight: 500;
    letter-spacing: 1px;
    border-radius: 5px;
    border: 1px dashed#dcdfe6;
    box-shadow:
      1px 1px 1px #f2f6fc,
      -1px -1px 1px #ebeef5;
    -webkit-transition: all 0.6s;
    -moz-transition: all 0.6s;
    transition: all 0.6s;
  }
  .upload-body:hover {
    border: 1px dashed#4e88f3;
  }
  .el-upload__text {
    font-size: 13px;
  }
  .el-upload__tip {
    font-size: 11px;
    letter-spacing: 1px;
  }
  .el-upload-list__item {
    width: 300px;
    background: #fafcff;
    border: 1px dashed#dcdfe6;
    box-shadow:
      1px 1px 1px #f2f6fc,
      -1px -1px 1px #ebeef5;
    -webkit-transition: all 0.4s;
    -moz-transition: all 0.4s;
    transition: all 0.4s;
    .el-upload-list__item-file-name {
      font-size: 13px;
    }
    .el-icon {
      font-size: 14px;
    }
  }
  // .el-upload-list__item:hover {
  //   border: 1px dashed#4e88f3;
  // }
}
</style>
